<template>
  <div class="container">
    <h3>drag-select</h3>
    <div class="box" ref="box"></div>
  </div>
</template>

<script>
var wId = 'w';
var index = 0;
var startX = 0;
var startY = 0;
var flag = false;
var retcLeft = '0px';
var retcTop = '0px';
var retcHeight = '0px';
var retcWidth = '0px';
var boxClientX = 0;
var boxClientY = 0;
export default {
  mounted() {
    this.$refs.box.addEventListener('mousedown', e => this.mousedowmHandle(e));
    this.$refs.box.addEventListener('mousemove', e => this.mousemoveHandle(e));
    this.$refs.box.addEventListener('mouseup', e => this.mouseupHandle(e));
  },
  methods: {
    mousedowmHandle(evt) {
      flag = true;
      try {
        index++;
        let div = document.createElement('div');
        let boxRect = this.$refs.box.getBoundingClientRect();
        boxClientX = boxRect.x;
        boxClientY = boxRect.y;
        startX = evt.clientX - boxClientX;
        startY = evt.clientY - boxClientY;
        div.id = wId + index;
        div.className = 'div';
        div.style.marginLeft = startX + 'px';
        div.style.marginTop = startY + 'px';
        this.$refs.box.appendChild(div);
      } catch (err) {}
    },
    mousemoveHandle(evt) {
      if (flag) {
        try {
          retcLeft =
            (startX - evt.clientX + boxClientX > 0
              ? evt.clientX - boxClientX
              : startX) + 'px';
          retcTop =
            (startY - evt.clientY + boxClientY > 0
              ? evt.clientY - boxClientY
              : startY) + 'px';
          retcHeight = Math.abs(startY - evt.clientY + boxClientY) + 'px';
          retcWidth = Math.abs(startX - evt.clientX + boxClientX) + 'px';
          let div = document.getElementById(wId + index);
          div.style.marginLeft = retcLeft;
          div.style.marginTop = retcTop;
          div.style.width = retcWidth;
          div.style.height = retcHeight;
        } catch (err) {}
      }
    },
    mouseupHandle(evt) {
      try {
        this.$refs.box.removeChild(document.getElementById(wId + index));
        let div = document.createElement('div');
        div.className = 'retc';
        div.style.marginLeft = retcLeft;
        div.style.marginTop = retcTop;
        div.style.width = retcWidth;
        div.style.height = retcHeight;
        this.$refs.box.appendChild(div);
        // 检查是否在区域内
      } catch (err) {}
      flag = false;
    },
  },
};
</script>


<style lang="less">
.box {
  width: 100%;
  height: 250px;
  border: 1px solid #f2f2f2;
  position: relative;
  overflow: hidden;
  .div {
    position: absolute;
    border: 1px dashed blue;
    width: 0px;
    height: 0px;
    left: 0px;
    top: 0px;
    overflow: hidden;
  }
  .retc {
    position: absolute;
    border: 1px solid #cccccc;
    overflow: hidden;
    background: #efefef;
  }
}
</style>